//
//  MatchViewController.m
//  MyDIYHouse
//
//  Created by dlios on 15-6-29.
//  Copyright (c) 2015年 李平洋. All rights reserved.
//

#import "MatchViewController.h"
#import "MatchCollectionViewCell.h"
#import "MatchSingleCollectionViewCell.h"
#import "MatchTableViewCell.h"
#import "MatchDetailViewController.h"
#import "MatchModel.h"
#import "HTTPTool.h"
#import "UIImageView+WebCache.h"
#import "UIButton+WebCache.h"
#import "SingleModel.h"
#import "MySingleCollectionViewCell.h"
#import "SingleDetailViewController.h"
#import "MJRefresh.h"   //1.上拉刷新 引头文件
//#import "StrategyDetailViewController.h"
#import "StylistDetailViewController.h"


#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

@interface MatchViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UITableViewDelegate, UITableViewDataSource>

@property(nonatomic, retain)UICollectionView *collectionView;
@property(nonatomic, retain)UITableView *tableView;

@property(nonatomic, retain)NSMutableArray *matchArray;

@property(nonatomic,retain)NSMutableArray *singleArr;
//几个参数写成属性
@property(nonatomic, assign)NSInteger start;    //2.上拉刷新  把start改成NSInteger
@property(nonatomic, copy)NSString *count;
@property(nonatomic, copy)NSString *user;
@property(nonatomic, copy)NSString *cate;
@property(nonatomic, copy)NSString *style;
@property(nonatomic, copy)NSString *color;

//第二页属性
@property(nonatomic, assign)NSInteger singleStart;
@property(nonatomic, copy)NSString *singleCount;
@property(nonatomic, copy)NSString *singleUser;
@property(nonatomic, copy)NSString *singleCate;
@property(nonatomic, copy)NSString *singleStyle;
@property(nonatomic, copy)NSString *singleColor;

@property (nonatomic,retain)UICollectionView *singleCollectionView;

@end
@implementation MatchViewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.matchArray = [NSMutableArray array];
        self.singleArr = [NSMutableArray array];
        self.start = 0;
        self.count = @"5";
        self.user = @"(null)";
        self.cate = @"0";
        self.style = @"0";
        self.color = @"0";
        
        self.singleStart = 0;
        self.singleCount = @"10";
        self.singleUser = @"(null)";
        self.singleCate = @"0";
        self.singleStyle = @"0";
        self.singleColor = @"0";
        
        [self createData];
    }
    return self;
}

#pragma mark 解析数据的方法
- (void)createData {
    //用拼接字符串的方式,根据参数获取接口的字符串
    NSString *urlStr = [NSString stringWithFormat:@"http://api.guju.com.cn/v2/photo/flownew?start=%ld&count=%@&user=%@&cate=%@&style=%@&color=%@", self.start, self.count, self.user, self.cate, self.style, self.color];     //3.上拉刷新 把 start 改成@ld
    //使用封装的AFN解析数据的方法解析数据
    [HTTPTool get:urlStr body:nil httpResult:JSON success:^(id result) {
        NSDictionary *dic = result;
        NSArray *photosArray = dic[@"photos"];
        for (NSDictionary *tempDic in photosArray) {
            MatchModel *match = [[MatchModel alloc] initWithDic:tempDic];
            //字典里套字典 ,用这种方式,单独提出数据
            [match setValuesForKeysWithDictionary:tempDic[@"user"]];
            [match setValuesForKeysWithDictionary:tempDic[@"user"][@"userImage"]];
            //语法糖的使用方法
            //            match.large = tempDic[@"user"][@"userImage"][@"large"];
            //            match.userName = tempDic[@"user"][@"userName"];
            
            // NSLog(@"%@", match.bId);
            [self.matchArray addObject:match];
            [match release];
        }
        [self.collectionView reloadData];
        [self.tableView reloadData];
        [self.tableView footerEndRefreshing];          //5.上拉刷新 停止刷新这次刷新,  告诉截止,
        [self.singleCollectionView footerEndRefreshing];
        
    } failure:^(NSError *error) {
        
    }];
    
    
    NSString *singleUrlStr = [NSString stringWithFormat:@"http://api.guju.com.cn/v2/product/productFlowNew?start=%ld&count=%@&user=%@&cate=%@&style=%@&color=%@", self.singleStart, self.singleCount, self.singleUser, self.singleCate, self.singleStyle, self.singleColor];
    //使用封装的AFN解析数据的方法解析数据
    [HTTPTool get:singleUrlStr body:nil httpResult:JSON success:^(id result) {
        NSDictionary *dic = result;
        NSArray *productsArr = dic[@"products"];
        for (NSDictionary *tempDic in productsArr) {
            SingleModel *singel = [[SingleModel alloc] initWithDic:tempDic];
            
            //            NSDictionary *myDic = tempDic[@"addresses"][0];
            //            [singel setValuesForKeysWithDictionary:myDic];
            
            
            [singel setValuesForKeysWithDictionary:tempDic[@"addresses"][0]];
            
            //[singel setValuesForKeysWithDictionary:tempDic[@"images" ]];
            
            //NSLog(@"%@",tempDic[@"images"][0]);
            singel.images =tempDic[@"images"];
            
            
            
            
            [self.singleArr addObject:singel];
            [singel release];
            
            
            [self.collectionView reloadData];
            [self.singleCollectionView reloadData];
            
            
            
        }
        
    } failure:^(NSError *error) {
        
    }];
    
    
    
    
    
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor brownColor];
    self.navigationItem.title = @"搭配";
    
#pragma mark 创建segmentedControl
    UISegmentedControl *seg = [[UISegmentedControl alloc] initWithItems:@[@"搭配",@"单品"]];
    seg.frame = CGRectMake(0, 0, 120, 27);
    
    seg.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar addSubview:seg];
    [seg addTarget:self action:@selector(segmentedClick:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = seg;
    
    
    
    
    
#pragma mark 创建collectionView
    //创建collectionView
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(WIDTH, HEIGHT - 64 - 49);
    //设置行间距
    flowLayout.minimumLineSpacing = 0;
    //设置列间距
    flowLayout.minimumInteritemSpacing = 0;
    //设置四周间距
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    //设置横向滑动
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame: CGRectMake(0, 0, WIDTH, HEIGHT - 64 - 49) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor grayColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.pagingEnabled = YES;
    //边界回弹
    //self.collectionView.bounces = NO;
    self.collectionView.contentSize = CGSizeMake(WIDTH * 2, HEIGHT - 64 - 49);
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[MatchCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    [self.collectionView registerClass:[MatchSingleCollectionViewCell class] forCellWithReuseIdentifier:@"reuse2"];
    
    
    
}

#pragma mark SegmentedControl点击方法
- (void)segmentedClick:(UISegmentedControl *)seg {
    if (seg.selectedSegmentIndex == 0) {
        self.collectionView.contentOffset = CGPointMake(0, 0);
    }
    if (seg.selectedSegmentIndex == 1) {
        self.collectionView.contentOffset = CGPointMake(WIDTH, 0);
    }
}

#pragma mark collectionView协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == self.singleCollectionView) {
        return self.singleArr.count;
        
    }else
    {
        return 2;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if(collectionView == self.singleCollectionView)
    {
        MySingleCollectionViewCell * cell= [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse10" forIndexPath:indexPath];
        //使用了注册,就不需要判断是否为空,(因为指定了不为空)
        cell.contentView.backgroundColor = [UIColor whiteColor];
        
        SingleModel *single = self.singleArr[indexPath.row];
        cell.CommodityNameLabel.text = single.title;
        cell.commentNamber.text = [single.commentNum stringValue];
        
        //房屋大图片
        
        [cell.CommodityImage sd_setImageWithURL:[NSURL URLWithString:single.images[0]]];
        //NSLog(@"%@", single.store);
        
        
        
        return cell;
    }
    else {
        if (indexPath.row == 0) {
            MatchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
            self.tableView = cell.myTableView;
#pragma mark 上拉加载方法
            
            [self.tableView addFooterWithCallback:^{     //4.上拉刷新 使用方法,实现上拉加载
                self.start = self.start + 5;
                [self createData];                     //上拉刷新  调用解析数据
                
            }];
            self.tableView.delegate = self;
            self.tableView.dataSource = self;
            return cell;
        } else {
            MatchSingleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse2" forIndexPath:indexPath];
            
            self.singleCollectionView =  cell.myCollectionView;
            
            [self.singleCollectionView addFooterWithCallback:^{
                self.singleStart = self.singleStart + 5;
                [self createData];
            }];
            self.singleCollectionView.delegate = self;
            self.singleCollectionView.dataSource = self;
            
            
            
            
            cell.backgroundColor = [UIColor whiteColor];
            return cell;
        }
    }
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SingleDetailViewController *singleDetailVC = [[SingleDetailViewController alloc] init];
    singleDetailVC.singleModel = self.singleArr[indexPath.row];
    // NSLog(@"%@",singleDetailVC.singleModel.title);
    [self.navigationController pushViewController:singleDetailVC animated:YES];
    [singleDetailVC release];
    
}


#pragma mark tableView协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.matchArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuse3 = @"reuse3";
    MatchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse3];
    if (!cell) {
        cell = [[[MatchTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse3] autorelease];
    }
    //房屋大图片
    MatchModel *match = self.matchArray[indexPath.row];
    NSString *picUrlStr = [NSString stringWithFormat:@"http://gooju.cn/dimages/%@_0_w%@_h%@_m0.jpg",match.bId, match.width, match.height];
    //NSLog(@"%@",picUrlStr);
    [cell.homeImageView sd_setImageWithURL:[NSURL URLWithString:picUrlStr]];
    
    //设计师头像
    
    [cell.headButton sd_setBackgroundImageWithURL:[NSURL URLWithString:[match.userImage objectForKey:@"large"]] forState:UIControlStateNormal];
    
    cell.headButton.tag = 10000+indexPath.row;
    [cell.headButton addTarget:self action:@selector(headButtonclick:) forControlEvents:UIControlEventTouchUpInside];
    
    //设计师名称
    cell.stylistName.text = match.userName;
    
    //收藏数量
    cell.starNumber.text = [match.ideabookNum stringValue];
    
    return cell;
}
#pragma mark 跳转到设计师主页
- (void)headButtonclick:(UIButton *)button
{
    NSInteger row = button.tag-10000;
    MatchModel *match = self.matchArray[row];
    StylistDetailViewController *styVC  = [[StylistDetailViewController alloc] init];
    styVC.myUserName = match.userName;
    [self.navigationController pushViewController:styVC animated:YES];
    [styVC release];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MatchDetailViewController *matchDetailVC = [[MatchDetailViewController alloc] init];
    matchDetailVC.matchModel = self.matchArray[indexPath.row];
    [self.navigationController pushViewController:matchDetailVC animated:YES];
    [matchDetailVC release];
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
